$.fn.modal.Constructor.prototype.enforceFocus = function () {};
$(function(){
	  $("#myModal1").on("shown.bs.modal", function(){
			 $("#domain_id").select2(commonSelect2Ajax("/production/domain"));
			 $("#department_id").select2(commonSelect2Ajax("/production/major"));
	   });
	   $("#myModal").on("shown.bs.modal", function(){
		     $("#major_id").select2(specialCommonSelect2Ajax("/production/major"));
		     $("#school_id").select2(commonSelect2Ajax("/student/school"));
       })
	    $("#hangye_id").select2(commonSelect2Ajax("/production/industry"));
	   
	   $("#videoshow").bind("click",function(){
		   	$("#videoModal").modal("show");
		   });
	   
	   String.prototype.endWith=function(endStr){
			  var d=this.length-endStr.length;
			  return (d>=0&&this.lastIndexOf(endStr)==d)
			}
});
function controlPageIsShow(isShow){
	if(isShow){
		$(document).bind("contextmenu", function() { return true; });
		 $("#background,#progressBar").hide();
		 $("body").removeClass("hideScoll");
	}else{
		$(document).bind("contextmenu", function() { return false; });
		 var top=$(document).scrollTop();
		 if(top>200){
			 top=($(document).height()+200)/2;
			 $("#progressBar").css("top",top);
		 }
		 $("#background").css("height",$(document).height()+top);
		 $("#background,#progressBar").show();
		 $("body").addClass("hideScoll");
	}
}
function uploadziliao(){
	if($("#dataupload").val()==""){
		commonAlert("上传资料不能为空！");
		return;
	};
	
	if(!$("#dataupload").val().endWith(".rar")){
		commonAlert("上传资料格式为rar！");
		return;
	};
	 var formData = new FormData($( "#uploadForm" )[0]); 
	controlPageIsShow(false);
    $.ajax({  
         url: '/production/uploadziliao' ,  
         type: 'POST',  
         data: formData,  
         cache: false,  
         contentType: false,  
         processData: false,  
         success: function (returndata) { 
        	 controlPageIsShow(true);
        	 if(returndata.error!=""){
        		 commonAlert(returndata.error);
        		 return;
        	 }
        	 commonAlert("上传成功！");
             $("#dataurla").attr("href","/production/downloaddata?name="+returndata.fileurl);
             $("#dataurldiv").attr("style","display: inline-block;");
             $("#dataurldiv").show();
         },  
         error: function (returndata) { 
        	 controlPageIsShow(true);
             commonAlert(returndata.fileurl);  
         }  
    });  
	
}

function endsubmit(id){
     bootbox.confirm({
			buttons : {
				confirm : {
					label : '确定',
					className : 'btn-myStyle'
				},
				cancel : {
					label : '取消',
					className : 'btn-default'
				}
			},
			message :"确认提交？提交后将不能再修改",
			callback : function(result) {
				if(result){
                       $.ajax({  
       						 url: '/production/endsubmit?id='+id,  
      						  type: 'POST',  
      						  async: false,  
        					cache: false,  
      						  contentType: false,  
       						 processData: false,  
        					success: function (returndata) {
        					if(returndata.error!=""){
        						commonAlert("当前上传资料为空！");
        						return;
        					}
       						 commonAlert("提交成功！");
       						  window.location.href="/production/listview";
       						 },  
       						 error: function (returndata) { 
           						 commonAlert("提交失败!");  
       						 }  
					 });
				}	 
			},
			title : "确认提示"
	 });
}


	
function uploadvideo(){
	if($("#videoupload").val()==""){
		commonAlert("上传视频不能为空！");
		return;
	};
	
	if(!$("#videoupload").val().endWith(".flv")){
		commonAlert("上传视频格式为flv！");
		return;
	};
	
	 var formData = new FormData($( "#uploadForm1" )[0]);  
	 controlPageIsShow(false);
    $.ajax({  
        url: '/production/uploadvideo' ,  
        type: 'POST',  
        data: formData,  
        cache: false,  
        contentType: false,  
        processData: false,  
        success: function (returndata) { 
        	controlPageIsShow(true);
        	if(returndata.error!=""){
       		 commonAlert(returndata.error);
       		 return;
       	 }
        	commonAlert("上传成功！");
            $("#videoshow").attr("type","text");
            addBtnEvent("videoshow", returndata.fileurl);
        },  
        error: function (returndata) {
        	controlPageIsShow(true);
            commonAlert("上传失败");  
        }  
   });  
	
}


function addBtnEvent(id,url){
   $("#"+id).bind("click",function(){
   	$("embed").attr("flashvars", "vcastr_file=/production/downloadvideo?name="+url+"&IsAutoPlay=0");
   	$("#videoModal").modal("show");
   });
}

function loadvideo(videoUrl){
	$('#videoModal').modal('show');
	$("embed").attr("flashvars", "vcastr_file=/production/downloadvideo?name="+videoUrl+"&IsAutoPlay=0");
}

function subaddauther(){
	var selfValid=true;
	if($("#myModal").find("select[id='school_id']").val()==null){
		$("#myModal").find(".selfError:eq(0)").show();
		selfValid=false;
	}
	if($("#myModal").find("select[id='major_id']").val()==null){
		$("#myModal").find(".selfError:eq(1)").show();
		selfValid=false;
	}
	var validResult=$("#addahther").valid();
	validResult=validResult&&selfValid;
	if(!validResult) return;
	$("#myModal").modal('hide');
$.ajax({
   url:"/production/addauther",
   type:"post",
   data:$("#addahther").serialize(),
   dataType:'json',
   success:function(json){
   	var data =json.data
   	for (var i = 0; i < data.length; i++) {
   		var row ="<tr id='"+data[i].authorsort+"' align='center' class='list-item' style='height: 35px;border-bottom: 1px solid #ccc;'>"+
   		"<td hidden='hidden'><input type='hidden' name='authorjson' value="+json.datastr+"></td>"+
			"<td><input type='hidden' name='authorname' value="+data[i].authorname+">"+data[i].authorname+"</td>"+
			"<td><input type='hidden' name='sex' value="+data[i].sex+">"+data[i].sex+"</td>"+
			"<td><input type='hidden' name='authordate' value="+data[i].authordate+">"+data[i].authordate+"</td>"+
			"<td><input type='hidden' name='authorschool' value="+data[i].authorschool+">"+data[i].authorschool+"</td>"+
			"<td><input type='hidden' name='authormajor' value="+data[i].authormajor+">"+data[i].authormajor+"</td>"+
			"<td><input type='hidden' name='length' value="+data[i].length+">"+data[i].length+"</td>"+
			"<td><input type='hidden' name='classes' value="+data[i].classes+">"+data[i].classes+"</td>"+
			"<td><input type='hidden' name='num' value="+data[i].num+">"+data[i].num+"</td>"+
			"<td><input type='hidden' name='mail' value="+data[i].mail+">"+data[i].mail+"</td>"+
			"<td><input type='hidden' name='phone' value="+data[i].phone+">"+data[i].phone+"</td>"+
			/*"<td><input type='hidden' name='authorsort' value="+data[i].authorsort+">"+data[i].authorsort+"</td>"+*/
			"<td><a onclick='delauthor("+data[i].authorsort+")' class='btn btn-link'>删除</a></td>"+
		"</tr>"
   		$("#authortable").append(row);
   		$("#oneauthor").hide();
   		$("#fiveauthor").hide();
		}
   }
});

}


function subaddteacher(){
	var validResult=$("#addteacher").valid();
	if(!validResult) return;
	$("#myModal1").modal('hide');
$.ajax({
   url:"/production/addteacher",
   type:"post",
   data:$("#addteacher").serialize(),
   dataType:'json',
   success:function(json){
   	var data =json.data
   	for (var i = 0; i < data.length; i++) {
   		var row ="<tr id='"+data[i].sort+"' align='center' class='list-item' style='height: 35px;border-bottom: 1px solid #ccc;'>"+
   		"<td hidden='hidden'><input type='hidden' name='teacherjson' value="+json.datastr+"></td>"+
			"<td>"+data[i].name+"</td>"+
			"<td>"+data[i].sex+"</td>"+
			"<td>"+data[i].date+"</td>"+
			"<td>"+data[i].department+"</td>"+
			"<td>"+data[i].title+"</td>"+
			"<td>"+data[i].level+"</td>"+
			"<td>"+data[i].domain+"</td>"+
			"<td>"+data[i].mail+"</td>"+
			"<td>"+data[i].phone+"</td>"+
			/*"<td>"+data[i].sort+"</td>"+*/
			"<td><a onclick='delauthor("+data[i].sort+")' class='btn btn-link'>删除</a></td>"+
		"</tr>"
   		$("#teachertable").append(row);
   		$("#twoteacher").hiden;
		}
   }
});

}


$(function(){
	$("select").each(function(index,element){
		$(element).change(function(){
			$(".errorself:eq("+index+")").hide();
		});
	});
	$("#myModal").find("select").each(function(index,element){
		$(element).change(function(){
			$(".selfError:eq("+index+")").hide();
		});
	});
	 $("table").trigger("update"); 
	 $("table").tablesorter({debug: true});
	 removeDuplicatePageInfo();	 
})
function CompareDate(d1,d2)
{
  return ((new Date(d1.replace(/-/g,"\/"))) > (new Date(d2.replace(/-/g,"\/"))));
}
function sub(){
	var writeType=true;
	if($("select[name='typeid']").val()==""){
		$(".errorself:eq(0)").show();
		writeType=false;
	}
	var industry=true;
	if($("#hangye_id").val()==""){
		$(".errorself:eq(1)").show();
		industry=false;
	}
	var validResult=$("#base_form").valid();
	
	if($("#authortable").find("tr").length<2){
		$("#oneauthor").show();
		return;
	}
	if($("#authortable").find("tr").length>6){
		$("#fiveauthor").show();
		return;
	}
	
	if($("#teachertable").find("tr").length>3){
		$("#oneteacher").show();
		return;
	}
	if($.trim($("#endtime1").val())!=""&&$.trim($("#starttime1").val())!=""){
		if(!CompareDate($("#endtime1").val(),$("#starttime1").val())){
			commonAlert("开始时间不能超过结束时间！");
			return;
		}
	}
	
	if(writeType&&industry&&validResult){
		bootbox.confirm({
			buttons : {
				confirm : {
					label : '确定',
					className : 'btn-myStyle'
				},
				cancel : {
					label : '取消',
					className : 'btn-default'
				}
			},
			message :"确定本页面所有信息都已填写完整？",
			callback : function(result) {
				if(result) {
					$("#base_form").submit();
				}
			},
			title : "确认提示"
		});
	}
}

function del(){
	 var ipts = $('input[type="checkbox"]:checked');
	 var id ="";
	 $.each(ipts,function(n,value) {   
   		 id+= value.value+",";
         });  
	 if(id==""){
		 commonAlert("请选择要删除的id");
		 return;
	 }
         bootbox.confirm({
			buttons : {
				confirm : {
					label : '确定',
					className : 'btn-myStyle'
				},
				cancel : {
					label : '取消',
					className : 'btn-default'
				}
			},
			message :"确认要删除选中的记录?",
			callback : function(result) {
				if(result) {
					 $.ajax({
		       				 url:"/production/del",
		     				type:"get",
		        			data:{id:id},
		        			dataType:'json',
		       				 success:function(json){
		        				$("#listForm").submit();
		       				 }
						});
				}
			},
			title : "确认提示"
	 });          
}

function delauthor(id){
            bootbox.confirm({
			buttons : {
				confirm : {
					label : '确定',
					className : 'btn-myStyle'
				},
				cancel : {
					label : '取消',
					className : 'btn-default'
				}
			},
			message :"确认要删除选中的记录?",
			callback : function(result) {
				if(result){
					  $("#"+id).remove();
				}				
			},
			title : "确认提示"
	 });
  
}
function specialCommonSelect2Ajax(url){
	return {
		  allowClear: true,
		  placeholder: "请选择",
  	      tokenSeparators: [','],
	      ajax: {
	          url: url,
	          dataType: 'json',
	          delay: 250,
	          data: function (params) {
	            return {
	              q: params.term, // search term
	              page: params.page
	            };
	          },
	          processResults: function (data, params) {
	            params.page = params.page || 1;
	            var result=[];
	            if(data){
	            	for(var i=0;i<data.length;i++){
	            		result.push({id:data[i].id,name:data[i].name,code:data[i].code});
	            	}
	            }
	            return {
	              results: result,
	              pagination: {
	                more: (params.page * 30) < data.total_count
	              }
	            };
	          },
	          cache: true
	        },
	        escapeMarkup: function (markup) { return markup; },
	        minimumInputLength: 1,
	        templateResult: specialFormatRepo,
	        templateSelection: specialFormatRepoSelection
	}
}
function specialFormatRepo (repo) {
	 if (repo.loading) return repo.text;
	 if(repo.id&&repo.name){
		 var markup = "<option value="+repo.name+">"+repo.code+"&nbsp;&nbsp;"+repo.name+"</option>";
		 return markup;
	 }
 }
function specialFormatRepoSelection (repo) {
	if(repo.selected) return repo.text;
   return repo.name;
 }

